package im.frape;

import im.frape.core.FrapeCore;
import im.frape.model.FrapeModel;

import java.util.ArrayList;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManager;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class ContactList extends Activity {
	private final static String TAG = "ContactList";
	private static ContactList instance;
	private FrapeCore core;
	private FrapeModel model;

	private ListView contactsListView;
	private ArrayAdapter<String> adapter;
	private ArrayList<String> array;

	public static ContactList getInstance() {
		return instance;
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "creating new ContactList");
		super.onCreate(savedInstanceState);
		instance = this;
		this.core = FrapeCore.getInstance();
		if (!this.core.isStarted()) {
			this.model = FrapeModel.getInstance();
			this.model.initialize(getPreferences(0), this.getApplicationContext());
			// this.model.setContext();
			setContentView(R.layout.contact_list);
			initContactsListView();

			initService();
		} else {

			this.model = this.core.getModel();

			setContentView(R.layout.contact_list);
			this.model.reconnectWithContactList();
			initContactsListView();

		}

	}

	private void initService() {
		Log.i(TAG, "service is going to be started");
		Intent svc = new Intent(this, FrapeCore.class);
		startService(svc);
		this.core.isStarted(true);
		Log.i(TAG, "service should be started");
	}

	private void initContactsListView() {
		contactsListView = (ListView) this.findViewById(R.id.contacts_list);
		contactsListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				XMPPConnection connection = ContactList.getInstance().model.getConnection("sindelar.fr@gmail.com");
				ChatManager chatmanager = connection.getChatManager();
				Chat newChat = chatmanager.createChat((String) contactsListView.getItemAtPosition(position),
						new MessageListener() {
							public void processMessage(Chat chat, Message message) {
								Log.i(TAG, message.getBody());
							}

						});

				try {
					newChat.sendMessage(".");
				} catch (XMPPException e) {
					System.out.println("Error Delivering block");
				}

			}

		});
		contactsListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				XMPPConnection connection = ContactList.getInstance().model.getConnection("sindelar.fr@gmail.com");
				ChatManager chatmanager = connection.getChatManager();
				Chat newChat = chatmanager.createChat((String) contactsListView.getItemAtPosition(position),
						new MessageListener() {
							public void processMessage(Chat chat, Message message) {
								Log.i(TAG, message.getBody());
							}

						});

				try {
					newChat.sendMessage("|");
				} catch (XMPPException e) {
					System.out.println("Error Delivering block");
				}
				return true;
			}

		});
		registerForContextMenu(findViewById(R.id.contacts_list));
		// ListView listView = (ListView) findViewById(R.id.contacts_list);
		// listView.setTextFilterEnabled(true);
		/*
		 * listView.setOnItemClickListener(new OnItemClickListener() {
		 * 
		 * @Override public void onItemClick(AdapterView<?> adapter, View view,
		 * int arg2, long arg3) { Toast.makeText(getApplicationContext(),
		 * ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
		 * 
		 * } });
		 */

		contactsListView.setAdapter(this.model.getArrayAdapter());
	}

	public void invalidateContactsListView() {
		this.contactsListView.refreshDrawableState();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.menu_accounts:
			try {
				Intent in = new Intent(this, AccountList.class);
				startActivity(in);
			} catch (Exception e) {
				Log.e(TAG, "Failed to launch Accounts Activity " + e.getMessage());
			}
			return true;

		case R.id.menu_settings:
			try {
				Intent in = new Intent(this, Settings.class);
				startActivity(in);
			} catch (Exception e) {
				Log.e(TAG, "Failed to launch Settings Activity " + e.getMessage());
			}
			return true;

		case R.id.menu_sign_out:
			Log.i(TAG, "Signing out from all accounts...");
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
